package com.qf.service.impl;

import com.qf.entity.SysUser;
import com.qf.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        SysUser sysUser = userMapper.loginByName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //根据用户id查询用户权限
        //List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("add,update");
        Set<String> authSet = userMapper.selectAuthsById(sysUser.getId());
        // 需要转换为 GrantedAuthority 类型
        Set<GrantedAuthority> auths = new HashSet<>();
        authSet.forEach(auth -> {
            auths.add(new SimpleGrantedAuthority(auth));
        });

        //返回用户信息及权限
        return new User(sysUser.getUsername(), sysUser.getPassword(),auths);
    }
}
